<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考勤日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeRecordDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['attendance:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['attendance:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['attendance:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['attendance:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考勤记录编号" align="center" prop="id" />
      <!--<el-table-column label="用户ID，关联员工表" align="center" prop="userId" />-->
      <!--<el-table-column label="用户的部门id" align="center" prop="deptId" />-->
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="职位名称" align="center" prop="positionName" />
      <el-table-column label="上班打卡时间" align="center" prop="clockInTime" width="180"/>
      <el-table-column label="下班打卡时间" align="center" prop="clockOutTime" width="180"/>

      <el-table-column label="实际上班时长(小时)" align="center" prop="actualWorkHours" />
      <el-table-column label="应上班时长(小时)" align="center" prop="requiredWorkHours" />
      <el-table-column label="加班时长(小时)" align="center" prop="overtimeHours" />
      <el-table-column label="考勤日期" align="center" prop="recordDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录创建时间" align="center" prop="createdAt" />
      <el-table-column label="迟到状态" align="center" prop="lateRecordStatus">
        <template #default="scope">
          <el-tag :type="getLateTagType(scope.row.lateRecordStatus)">
            {{ formatLateStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="早退状态" align="center" prop="earlyRecordStatus">
        <template #default="scope">
          <el-tag :type="getEarlyTagType(scope.row.earlyRecordStatus)">
            {{ formatEarlyStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="加班状态" align="center" prop="overtimeRecordStatus">
        <template #default="scope">
          <el-tag :type="getOvertimeTagType(scope.row.overtimeRecordStatus)">
            {{ formatOvertimeStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column label="迟到状态" align="center" prop="lateRecordStatus"-->
      <!--                 :formatter="formatLateStatus">-->
      <!--</el-table-column>-->

      <!--<el-table-column label="早退状态" align="center" prop="earlyRecordStatus"-->
      <!--                 :formatter="formatEarlyStatus">-->
      <!--</el-table-column>-->

      <!--<el-table-column label="加班状态" align="center" prop="overtimeRecordStatus"-->
      <!--                 :formatter="formatOvertimeStatus">-->
      <!--</el-table-column>-->
<!--      <el-table-column label="打卡状态:-->
<!--0: 暂定-->
<!--1: 正常-->
<!--2: 迟到" align="center" prop="earlyRecordStatus" />-->
<!--      <el-table-column label="打卡状态:-->
<!--0: 暂定-->
<!--1: 正常-->
<!--3: 早退" align="center" prop="lateRecordStatus" />-->
<!--      <el-table-column label="打卡状态:-->
<!--0: 暂定-->
<!--1: 正常-->
<!--2: 无加班" align="center" prop="overtimeRecordStatus" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['attendance:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['attendance:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工考勤记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID，关联员工表" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID，关联员工表" />
        </el-form-item>
        <!--<el-form-item label="实际上班打卡时间" prop="deptId">-->
        <!--  <div class="block">-->
        <!--    <span class="demonstration">With default time</span>-->
        <!--    <el-date-picker-->
        <!--        v-model="form.clockInTime"-->
        <!--        type="datetime"-->
        <!--        placeholder="Select date and time"-->
        <!--        :default-time="defaultTime"-->
        <!--    />-->
        <!--  </div>-->
        <!--</el-form-item>-->
        <el-form-item label="实际上班打卡时间" prop="clockInTime">
          <el-date-picker clearable
            v-model="form.clockInTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择实际上班打卡时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际下班打卡时间" prop="clockOutTime">
          <el-date-picker clearable
            v-model="form.clockOutTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择实际下班打卡时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考勤日期" prop="recordDate">
          <el-date-picker clearable
            v-model="form.recordDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择考勤日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-input v-model="form.createdAt" placeholder="请输入记录创建时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/attendance/record"
import {parseTime} from "../../../utils/ruoyi.js";

const { proxy } = getCurrentInstance()

const recordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeRecordDate = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    recordDate: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户ID，关联员工表不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询员工考勤记录列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeRecordDate && '' != daterangeRecordDate) {
    queryParams.value.params["beginRecordDate"] = daterangeRecordDate.value[0]
    queryParams.value.params["endRecordDate"] = daterangeRecordDate.value[1]
  }
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    deptId: null,
    userName: null,
    departmentName: null,
    positionName: null,
    clockInTime: null,
    clockOutTime: null,
    actualWorkHours: null,
    requiredWorkHours: null,
    overtimeHours: null,
    recordDate: null,
    delFlag: null,
    createdAt: null,
    earlyRecordStatus: null,
    lateRecordStatus: null,
    overtimeRecordStatus: null
  }
  proxy.resetForm("recordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeRecordDate.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加员工考勤记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecord(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改员工考勤记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除员工考勤记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecord(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('attendance/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}


function getLateTagType(status) {
  switch (status) {
    case 0: return 'info';    // 灰色
    case 1: return 'success'; // 绿色
    case 2: return 'danger';  // 红色
    default: return 'info';
  }
}

// 获取早退状态的标签类型
function getEarlyTagType(status) {
  switch (status) {
    case 0: return 'info';
    case 1: return 'success';
    case 2: return 'danger';
    default: return 'info';
  }
}

// 获取加班状态的标签类型
function getOvertimeTagType(status) {
  switch (status) {
    case 0: return 'info';
    case 1: return 'success';
    case 2: return 'warning'; // 加班状态使用黄色表示无加班更合适
    default: return 'info';
  }
}




// 格式化迟到状态
function formatLateStatus(row) {
  const statusMap = {
    0: '暂定',
    1: '正常',
    2: '迟到'
  };
  return statusMap[row.lateRecordStatus] || '未知';
}

// 格式化早退状态
function formatEarlyStatus(row) {
  const statusMap = {
    0: '暂定',
    1: '正常',
    2: '早退'
  };
  return statusMap[row.earlyRecordStatus] || '未知';
}

// 格式化加班状态
function formatOvertimeStatus(row) {
  const statusMap = {
    0: '暂定',
    1: '有加班',
    2: '无加班'
  };
  return statusMap[row.overtimeRecordStatus] || '未知';
}

getList()
</script>


<style scoped>
.attendance-page {
  padding: 20px;
}

/* 可选：添加状态样式 */
.status-normal {
  color: #67c23a; /* 绿色 */
}
.status-late {
  color: #f56c6c; /* 红色 */
}
.status-early {
  color: #e6a23c; /* 橙色 */
}
</style>
